package com.fjwt.gz.service.activity.platform.acte028;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityAwardBO;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.dto.FansAwardDTO;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.FansCouponsVo;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.ActivityAwardService;
import com.fjwt.gz.service.impl.ActivitySettingService;
import com.fjwt.gz.service.impl.AgentInfoService;
import com.fjwt.gz.service.impl.AwardSettingService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.SendAwardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商户资产提升活动------
 */
@Slf4j
@Service
public class ACTE028Service extends BaseActivityService<Object> {

    private static String logPrefix = "【商户资产提升活动】";
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE028的活动");
        if (0 != activityDTO.getState()) {
            List<BaseActivityDTO.ActivityAward> activityAwardList = activityDTO.getActivityAwardList();
            if (ObjectUtils.isEmpty(activityAwardList)) {
                throw new BizException("请绑定活动奖品");
            }
            int size = activityAwardList.size();
            if (size < 4 || size > 8) {
                throw new BizException("活动奖品需4-8个");
            }
        }
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE028的活动");
        if (0 != activityDTO.getState()) {
            List<BaseActivityDTO.ActivityAward> activityAwardList = activityDTO.getActivityAwardList();
            if (ObjectUtils.isEmpty(activityAwardList)) {
                throw new BizException("请绑定活动奖品");
            }
            int size = activityAwardList.size();
            if (size < 4 || size > 8) {
                throw new BizException("活动奖品需4-8个");
            }
        }
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE028的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE028的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }

    @Override
    public JSONObject getActivityAwards(FansActivityDTO fansActivityDTO) {
        JSONObject jsonObject = new JSONObject();
        // 查询用户领取活动卡券详情
        List<FansCouponsVo> fansActivateCoupon = fansAwardService.findFansActivateCoupons(fansActivityDTO);
        if (ObjectUtils.isNotEmpty(fansActivateCoupon)) {
            jsonObject.put("couponList", fansActivateCoupon);
            FansCouponsVo fansCouponsVo = fansActivateCoupon.stream().min(Comparator.comparingInt(vo -> vo.getCouponNum() - vo.getCouponGet())).get();
            jsonObject.put("stock", fansCouponsVo.getCouponNum() - fansCouponsVo.getCouponGet());
            jsonObject.put("percent", new BigDecimal(fansCouponsVo.getCouponNum() - fansCouponsVo.getCouponGet()).divide(new BigDecimal(fansCouponsVo.getCouponNum()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
        }
        // 查询活动已激活卡券用户详情
        List<FansAwardDTO> activityUnusedCoupon = fansAwardService.findActivityUnusedCoupon(fansActivityDTO);
        jsonObject.put("fansPhoneList", activityUnusedCoupon);
        return jsonObject;
    }

    /**
     * 参与活动发放奖品
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入{}", logPrefix);
        super.takePartIn(fansActivityDTO);
        Long activityId = fansActivityDTO.getActivityId();

        AgentInfoEntity agentInfoEntity = agentInfoService.getAgentInfo(fansActivityDTO.getLocationAgentNo());

        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        // 发放奖品额外参数
        JSONObject extJsonObject = new JSONObject();
        extJsonObject.put("activityId", activityId);
        extJsonObject.put("templateNo", "ACTE028");

        // 获取活动奖品
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        List<ActivityAwardBO> activityAwardBOList = activityAwardService.getAwardList(activityAwardList);
        for (ActivityAwardBO activityAwardBO : activityAwardBOList) {
            log.info("活动奖品详细信息:{}", JSONUtil.toJsonStr(activityAwardBO));
            if (activityAwardBO.getAwardNum() - activityAwardBO.getAwardGet() < 1) {
                throw new BizException("该活动奖品已发放完毕");
            }
            long fansAwardId = sendAwardService.sendActivateAward(fansActivityDTO.getFansId(), fansActivityDTO.getAppId(), activityAwardBO.getAwardId(),
                    activityAwardBO.getAwardType(), endDate, activityAwardBO.getRemark(), fansActivityDTO.getActivityChannelId(),
                    null, extJsonObject.toJSONString(), agentInfoEntity);
            activityAwardBO.setFansAwardId(fansAwardId);
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }
        return activityAwardService.toUserData(null);
    }
}
